﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using System.Windows.Forms.Design;
using System.Windows.Forms;
using EnvDTE;
using System.IO;
using VsxFactory.Modeling.VisualStudio;

namespace VsxFactory.Modeling.StrategyManager
{
    class DependentFileEditor : ExtenderTypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if ((provider != null) && (((IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService))) != null))
            {
                ProjectItem pi = GetProjectItem(context);
                if (pi != null)
                {
                    var fileDialog = new OpenFileDialog();
                    fileDialog.InitialDirectory = Path.GetDirectoryName(pi.FileNames[0]);
                    fileDialog.CheckFileExists = true;
                    fileDialog.Title = "Dependent file editor";

                    if (value != null)
                    {
                        fileDialog.FileName = value.ToString();
                    }
                    if (fileDialog.ShowDialog() == DialogResult.OK)
                    {
                        string projectDir = Path.GetDirectoryName(pi.FileNames[0]);
                        string s = Utils.PathRelativePathToFolder( projectDir, fileDialog.FileName);
                        if (!String.IsNullOrWhiteSpace(s) && s[0] == Path.DirectorySeparatorChar)
                            s = s.Substring(1);
                        value = s;
                    }
                }
            }
            return value;
        }
    }
}
